<template>
  <div v-if="dialogVisble">
    <el-dialog title="上传文件" :visible.sync="dialogVisble" :before-close="handleClose" :close-on-click-modal=false
               width="40%" destroy-on-close>
      <el-form label-width="120px" style="padding-right: 30px;" :model="uploadFileForm" :rules="rules"
               ref="uploadFileForm">
        <el-form-item label="文件名称" prop="name">
          <el-input size="small" style="width: 90%" v-model="uploadFileForm.name" placeholder="请输入文件名称" maxlength="50"/>
        </el-form-item>
        <el-form-item label="文件描述" prop="description">
          <el-input size="small" style="width: 90%" v-model="uploadFileForm.description" :autosize="{ minRows: 3}"
                    maxlength="200" show-word-limit type="textarea" clearable placeholder="请输入文件描述"/>
        </el-form-item>
        <el-form-item label="选择文件" prop="fileList">
          <el-upload class="upload-demo" :file-list="uploadFileForm.fileList" :before-upload="beforeUpload"
                     :http-request="uploadFile"
                     accept=".xls, .xlsx, .png, .pdf, .jpg, .jpeg, .md, .txt, .doc, .docx, .html, .htm"
                     :on-remove="removeFile" :on-exceed="handleExceed" drag action="" :limit="1" ref="upload">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传单个后缀为 xls, xlsx, png, pdf, jpg, jpeg, md, txt, doc, docx, html, htm 的文件，且不超过5M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取消</el-button>
        <el-button size="small" type="primary" @click="submitFileForm">上传</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
export default {
  name: "uploadDialog",
  props: ["dialogVisble", "currentUser"],
  data() {
    return {
      uploadFileForm: {
        name: "",
        description: "",
        fileList: [],
        filePath: ""
      },
      rules: {
        name: [{required: true, message: '文件名称不能为空', trigger: 'blur'}],
        fileList: [{required: true, message: '文件不能为空', trigger: 'change'}]
      },
    }
  },
  methods: {
    submitFileForm() {
      console.log("uploadFileForm", this.uploadFileForm)
      this.uploadFileForm["createUser"] = this.currentUser;
      this.$refs.uploadFileForm.validate(valid => {
        if (valid) {
          this.api({
            url: "/addFile",
            method: "post",
            data: this.uploadFileForm
          }).then(resp => {
            this.$message({message: resp, type: 'success'});
            this.handleClose();
            this.$emit("refreshList");
          });
        }
      })
    },
    handleClose() {
      this.$emit("closeDialog")
      this.uploadFileForm = {
        name: "",
        description: "",
        fileList: [],
        filePath: ""
      }
    },
    // 上传前判断格式和大小
    beforeUpload(file) {
      let FileExt = file.name.replace(/.+\./, "");
      if (['xls', 'xlsx', 'png', 'pdf', 'jpg', 'jpeg', 'md', 'txt', 'doc', 'docx', 'html', 'htm'].indexOf(FileExt.toLowerCase()) === -1) {
        this.$message({
          type: 'warning',
          message: '请上传后缀名为xls、xlsx、png、pdf、jpg、jpeg、md、txt、doc、docx、html、htm的附件！'
        });
        return false;
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.warning('文件大小超过5M 无法上传');
        return false;
      }
      return true;
    },
    handleExceed() {
      this.$message.warning('一次最多只能上传一个文件');
    },
    uploadFile(option) {
      console.log(option)
      let FormDatas = new FormData()
      FormDatas.append('file', option.file);
      this.uploadFileForm.fileList.push(option.file);
      this.uploadFileForm.name = option.file.name;
      this.$refs.uploadFileForm.validateField('fileList');
      this.api({
        url: "/upload",
        method: "post",
        data: FormDatas,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(resp => {
        this.uploadFileForm.filePath = resp;
      });
    },
    removeFile() {
      this.uploadFileForm.fileList = [];
    }
  }
}
</script>

<style scoped>

</style>
